package com.blakequ.androidblemanager.service;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.le.ScanFilter;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.blakequ.androidblemanager.R;
import com.blakequ.androidblemanager.containers.BluetoothLeDeviceStore;
import com.blakequ.androidblemanager.event.UpdateEvent;
import com.blakequ.androidblemanager.ui.MainPage;
import com.blakequ.androidblemanager.utils.BLEUtil;
import com.blakequ.androidblemanager.utils.BeaconModel;
import com.blakequ.androidblemanager.utils.BluetoothUtils;
import com.blakequ.androidblemanager.utils.Constants;
import com.blakequ.bluetooth_manager_lib.device.BeaconType;
import com.blakequ.bluetooth_manager_lib.device.BeaconUtils;
import com.blakequ.bluetooth_manager_lib.device.BluetoothLeDevice;
import com.blakequ.bluetooth_manager_lib.device.ibeacon.IBeaconDevice;
import com.blakequ.bluetooth_manager_lib.scan.BluetoothScanManager;
import com.blakequ.bluetooth_manager_lib.scan.ScanOverListener;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanCallbackCompat;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanFilterCompat;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanResultCompat;
import com.orhanobut.logger.Logger;
import com.pgyer.pgyersdk.PgyerSDKManager;
import com.tamsiree.rxkit.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service
{
	public static final String MY_UUID = "c59a3b46-51f7-4f26-a0fa-b9bce835b733";
	private BluetoothLeDeviceStore mDeviceStore;
	private BluetoothUtils mBluetoothUtils;
	private BluetoothScanManager scanManager;
	List<BeaconModel> beaconModelList = new ArrayList<>();
	public static int NOTIFICATION_ID = 101;
	private static final String TAG = "MyService";
	AlarmManager mAlarmManager = null;
	PendingIntent mPendingIntent = null;
//    BackgroundPowerSaver backgroundPowerSaver;
	public static boolean serviceIsLive = false;
	int count = 0;
	long onReceiveTimes = 0;// 接收次数
//	SocketClient socketClient;
//	private UdpClientBiz udpClientBiz = new UdpClientBiz();//初始化客户端的，以便需要用的地方来使用
	Timer timer = new Timer();
	TimerTask timerTask = new TimerTask() {
		@Override
		public void run() {

			Log.d("BD-Debug", ++count + " : "+System.currentTimeMillis()+"");
//			BDManager.getInstance().sendTestData(MyService.this);
			submitBle();
		}
	};
//	public static List<BDModel> list = new ArrayList<>();
	@Override
	public void onCreate()
	{
		//start the service through alarm repeatly
//	    Intent intent = new Intent(getApplicationContext(), MyService.class);
//		mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//		mPendingIntent = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//		long now = System.currentTimeMillis();
//		mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 300, mPendingIntent);
//		Toast.makeText(getApplicationContext(), "onCreate!", Toast.LENGTH_SHORT).show();
		Log.i(TAG,"onCreate");
		// 获取服务通知
		Notification notification = createForegroundNotification();
		//将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
		startForeground(NOTIFICATION_ID, notification);
//		Toast.makeText(getApplicationContext(), "onStartCommand!", Toast.LENGTH_SHORT).show();
		Log.i(TAG,"onStartCommand");
		Log.d("BD-Debug", "onStartCommand");
//		BDManager.getInstance().onCreate(this);
		startTimer();
		//调用sendMsg方法，传入发送的消息与实现OnMsgReturnedListener
//		udpClientBiz.sendMsg("xiachao", new UdpClientBiz.OnMsgReturnedListener() {
//			@Override
//			public void onMsgReturned(String msg) {
//				//收到的信息
////				textView.append("server:"+msg+"\n");
//				Log.e("MyService","UDPClient:收到消息："+msg);
//				EventBus.getDefault().post(EventUWB.newBuilder().content(msg).build());
//			}
//
//			@Override
//			public void onError(Exception ex) {
//				ex.printStackTrace();//有错误打印出错误
//				Log.e("MyService","UDPClient:Error报错："+ex.toString());
//			}
//		});

		startSocket();
		EventBus.getDefault().register(this);
		initScan();
		super.onCreate();
	}

	public void startSocket() {
//		if (socketClient != null) {
//			socketClient.close();
//			socketClient = null;
//		}
//		if (socketClient == null) {
//			socketClient = new SocketClient();
//			socketClient.start();
//		}
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{

//		startTimer();
		return START_STICKY;
	}

	private void startTimer() {
		try {
			Log.d("BD-Debug", "startTimer");
//			if (timer != null) {
//				timer.cancel();
//			}
			timer.schedule(timerTask,0,15000);
			Log.d("BD-Debug", "startTimer success");
		} catch (Exception e) {
			PgyerSDKManager.reportException(e);
		    if (e != null) {
		        Log.e("",""+e.toString());
				Log.d("BD-Debug", "startTimer ： "+e.toString());
		    }
		}
	}


	/**
	 * 返回一个Binder对象
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new MsgBinder();
	}


	@Override
	public void onDestroy() {
		Log.e("BD-Debug", "MyService - onDestroy");
		// 标记服务关闭
		serviceIsLive = false;
		// 移除通知
		stopForeground(true);
//		BDManager.getInstance().onDestroy();
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}



	/**
	 * 创建服务通知
	 */
	private Notification createForegroundNotification() {
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		// 唯一的通知通道的id.
		String notificationChannelId = "notification_channel_id_01";

		// Android8.0以上的系统，新建消息通道
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			//用户可见的通道名称
			String channelName = "BLE定位服务";
			//通道的重要程度
			int importance = NotificationManager.IMPORTANCE_HIGH;
			NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
			notificationChannel.setDescription("BLE定位服务正在运行");
			//LED灯
			notificationChannel.enableLights(true);
			notificationChannel.setLightColor(Color.RED);
			//震动
//			if (!BuildConfig.DEBUG) {
//				notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
//				notificationChannel.enableVibration(true);
//			}
			if (notificationManager != null) {
				notificationManager.createNotificationChannel(notificationChannel);
			}
		}

		NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
		//通知小图标
		builder.setSmallIcon(R.mipmap.ic_launcher);
		//通知标题
		builder.setContentTitle("BLE定位服务");
		//通知内容
		builder.setContentText("BLE定位正在运行");
		//设定通知显示的时间
		builder.setWhen(System.currentTimeMillis());
		//设定启动的内容
		Intent activityIntent = new Intent(this, MainPage.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(pendingIntent);

		//创建通知并返回
		return builder.build();
	}

	private void startBleScan() {

	}


	private  void startAlarmManager() {
		Intent intent =new Intent(this, MyService.class);
		PendingIntent sender=PendingIntent
				.getService(this, 0, intent, 0);
		AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
		alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5*1000,sender);
	}

	public class MsgBinder extends Binder {
		/**
		 * 获取当前Service的实例
		 * @return
		 */
		public MyService getService(){
			return MyService.this;
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEvent(UpdateEvent event){
//		startSocket();
	}


//	@Subscribe(threadMode = ThreadMode.MAIN)
//	public void onEvent(EventSwitch event){
//		if (socketClient != null) {
//			socketClient.close();
//			socketClient = null;
//		}
//		if (socketClient == null) {
//			socketClient = new SocketClient();
//			socketClient.start();
//		}
//	}


	private void initScan(){
		if (RxActivityTool.currentActivity() == null || RxActivityTool.getActivityStack() == null || RxActivityTool.getActivityStack().isEmpty()) {
			return;
		}
		Activity activity = null;
		for (Activity activity1 : RxActivityTool.getActivityStack()) {
			activity = activity1;
			if (activity != null) {
				break;
			}
		}
		mBluetoothUtils = new BluetoothUtils(activity);
		mDeviceStore = new BluetoothLeDeviceStore();
		BLEUtil.getInstance().setmBluetoothUtils(mBluetoothUtils);
		BLEUtil.getInstance().setmDeviceStore(mDeviceStore);
		scanManager = BluetoothScanManager.getInstance(this);
		scanManager.setScanOverListener(new ScanOverListener() {
			@Override
			public void onScanOver() {
				if (scanManager.isPauseScanning()){
//					invalidateOptionsMenu();
					Logger.i("扫描结果：-----结束");
				}
			}
		});
		scanManager.setScanCallbackCompat(new ScanCallbackCompat() {
			@Override
			public void onBatchScanResults(List<ScanResultCompat> results) {
				Logger.i("scan device results: "+results.size());
				super.onBatchScanResults(results);
			}

			@Override
			public void onScanFailed(final int errorCode) {
				Logger.i("scan device errorCode"+errorCode);
				super.onScanFailed(errorCode);
//				Snackbar.make(fab, "Fail to scan device! error code:" + errorCode, Snackbar.LENGTH_LONG)
//						.setAction("Detail", new View.OnClickListener() {
//							@Override
//							public void onClick(View v) {
//								if (errorCode == SCAN_FAILED_LOCATION_CLOSE){
//									ToastX.show("Location is closed, you should open first");
//								}else if(errorCode == SCAN_FAILED_LOCATION_PERMISSION_FORBID){
//									ToastX.show("You have not permission of location");
//								}else{
//									ToastX.show("Other exception");
//								}
//							}
//						}).show();
			}

			@Override
			public void onScanResult(int callbackType, ScanResultCompat result) {
					//uuid:c59a3b46-51f7-4f26-a0fa-b9bce835b733
				super.onScanResult(callbackType, result);
//				String deviceName = result.getScanRecord().getDeviceName();
//				if (deviceName != null) deviceName = deviceName.toLowerCase();

				if (BeaconUtils.getBeaconType(result.getLeDevice()) == BeaconType.IBEACON) {
					IBeaconDevice iBeacon = new IBeaconDevice(result.getLeDevice());
					if (TextUtils.isEmpty(iBeacon.getUUID()) || !iBeacon.getUUID().equals(MY_UUID)) {
						return;
					}
					mDeviceStore.addDevice(result.getLeDevice());
					String major = String.valueOf(iBeacon.getMajor());
					String minor = String.valueOf(iBeacon.getMinor());
					int rssi = iBeacon.getRssi();
					onReceiveTimes++;
					Logger.i("第"+onReceiveTimes+"次扫描结果 "+(scanManager.isBackgroundMode()?"后台运行 ":"前台运行")+ "major:"+major + " minor:"+minor + " rssi:"+rssi);
				}
//				if (true) {
////					if (filterRssi <= result.getRssi()) {
////						if (filterName == null || filterName.equals("")) {
////							mDeviceStore.addDevice(result.getLeDevice());
////						} else if (filterName.toLowerCase().equals(deviceName)) {
////							mDeviceStore.addDevice(result.getLeDevice());
////							//saveFileLog(result.getDevice().getAddress(), result.getScanRecord().getBytes(), result.getLeDevice().getTimestamp());
////						}
////					}
//					if (BeaconUtils.getBeaconType(result.getLeDevice()) == BeaconType.IBEACON) {
//						mDeviceStore.addDevice(result.getLeDevice());
//					}
//				} else {
//					mDeviceStore.addDevice(result.getLeDevice());
//				}
				UpdateEvent updateEvent = new UpdateEvent(UpdateEvent.Type.SCAN_UPDATE);
				updateEvent.setStore(mDeviceStore);
				updateEvent.setReceiveTimes(onReceiveTimes);
				EventBus.getDefault().post(updateEvent);
			}
		});
//		scanManager.setBackgroundMode(true);
//		scanManager.startScanNow();
//        backgroundPowerSaver = new BackgroundPowerSaver(this);
		ScanFilter.Builder builder = null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//			builder = new ScanFilter.Builder();
//			builder.setManufacturerData(0x004c, new byte[] {});
//			ScanFilter filter = builder.build();
//			new ScanFilterCompat.Builder().setManufacturerData(0x004c,new byte[] {});
//			scanManager.addScanFilterCompats();
		}


//        scanManager.addScanFilterCompats(new ScanFilterCompat.Builder()..setDeviceAddress("0C:EC:80:FF:12:91").build());
//		String serviceUuidString = "0000feaa-0000-1000-8000-00805f9b34fb";
//		String serviceUuidString = "C59A3B46-51F7-4F26-A0FA-B9BCE835B733";
//		String serviceUuidString = "c59a3b46-51f7-4f26-a0fa-b9bce835b733";
//		String serviceUuidString = "C59A3B46-51F7-4F26-A0FA-B9BCE835B733";

		String serviceUuidMaskString = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
		ScanFilterCompat scanFilterCompat = new ScanFilterCompat.Builder().setServiceUuid(null,ParcelUuid.fromString(serviceUuidMaskString))
				.build();
//		ScanFilterCompat scanFilterCompat = new ScanFilterCompat.Builder().setServiceUuid(ParcelUuid.fromString(serviceUuidString),ParcelUuid.fromString(serviceUuidMaskString))
//				.build();
//		scanManager.addScanFilterCompats(new ScanFilterCompat.Builder().setManufacturerData(0x004c,new byte[] {}).build());
//		scanManager.setScanSettings();
//		scanManager.getPowerSaver().setBackgroundScanPeriod(5000);
//		scanManager.getPowerSaver().setBackgroundBetweenScanPeriod(5000);
//		scanManager.getPowerSaver().setForegroundScanPeriod(3000);
//		scanManager.getPowerSaver().setForegroundBetweenScanPeriod(3000);
		scanManager.addScanFilterCompats(scanFilterCompat);
		scanManager.startCycleScan();
		startAlarmManager();
	}


	/**
	 * 前8位截取逻辑
	 * context.setMsgId(context.getData().substring(0, 2));// 蓝牙id固定 = 01
	 * context.setBattery(Integer.parseInt(context.getData().substring(2, 4), 16)); = 电池
	 * context.setTemperature(Integer.parseInt(context.getData().substring(4, 6), 16)); = 温度
	 * context.setMsgLength(Integer.parseInt(context.getData().substring(6, 8), 16)); = 总消息长度
	 * 10位截取逻辑
	 * beaconRequest.setMajor(String.valueOf(Integer.valueOf(info.substring(0, 4), 16))); = major
	 * beaconRequest.setMinor(String.valueOf(Integer.valueOf(info.substring(4, 8), 16))); = minor
	 * beaconRequest.setRssi(Integer.valueOf(info.substring(8, 10), 16) - 255); = 距离
	 *
	 *
	 */
	private void submitBle() {
		if (mDeviceStore == null || mDeviceStore.getDeviceList() == null || mDeviceStore.getDeviceList().isEmpty()) {
			return;
		}
		StringBuffer sb = new StringBuffer();
		List<BluetoothLeDevice> list =  mDeviceStore.getDeviceList();// 自动进行了排列组合
		if (list == null || list.isEmpty()) {
			return;
		}
		UpdateEvent updateEvent = new UpdateEvent(UpdateEvent.Type.SCAN_UPDATE);
		updateEvent.setStore(mDeviceStore);
		updateEvent.setReceiveTimes(onReceiveTimes);
		EventBus.getDefault().post(updateEvent);

		List<BluetoothLeDevice> subList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			if (!BLEUtil.isTooLong(list.get(i).getTimestamp())) {
				subList.add(list.get(i));
			}
			else{
				IBeaconDevice iBeacon = new IBeaconDevice(list.get(i));
				String lastTime =
						android.text.format.DateFormat.format(
								Constants.TIME_FORMAT, new java.util.Date(list.get(i).getTimestamp())).toString();
				Logger.i("设备超时不上传,major:"+iBeacon.getMajor() + " minor:"+iBeacon.getMinor() +" 超时时间："+lastTime);
			}
		}
		if (subList.isEmpty()) {
			return;
		}
		int max = 4;// 最多允许4个
//		sb.append("012600");
		sb.append("01");
		sb.append(intToHex(getPower(),2));// 电池
		sb.append("00");// 温度
		int length = (subList.size()*10+8);// 10*n + 8位固定长度
		String lengthStr = intToHex(length,0);
		sb.append(lengthStr);
		for (int i = 0; i < subList.size(); i++) {
			if (i < max) {
				IBeaconDevice iBeacon = new IBeaconDevice(subList.get(i));
				String major = String.valueOf(iBeacon.getMajor());
				String minor = String.valueOf(iBeacon.getMinor());
				int rssi = iBeacon.getRssi();
				int absRssi = 255 - Math.abs(rssi) ;
//				BeaconModel beaconModel = BeaconModel.newBuilder().major(major).minor(minor).rssi(absRssi).build();
				sb.append(intToHex(iBeacon.getMajor(),4));
				sb.append(intToHex(iBeacon.getMinor(),4));
				sb.append(intToHex(absRssi,2));
			}
		}
		String data = sb.toString();
		BLEUtil.getInstance().requestSubmit(data);

	}



//	if (BeaconUtils.getBeaconType(device) == BeaconType.IBEACON) {
//	final IBeaconDevice iBeacon = new IBeaconDevice(device);
//	final String accuracy = Constants.DOUBLE_TWO_DIGIT_ACCURACY.format(iBeacon.getAccuracy());
//
//	viewHolder.deviceIcon.setImageResource(R.mipmap.ic_device_ibeacon);
//	viewHolder.ibeaconSection.setVisibility(View.VISIBLE);
//	viewHolder.ibeaconMajor.setText(String.valueOf(iBeacon.getMajor()));
//	viewHolder.ibeaconMinor.setText(String.valueOf(iBeacon.getMinor()));
//	viewHolder.ibeaconTxPower.setText(String.valueOf(iBeacon.getCalibratedTxPower()));
//	viewHolder.ibeaconUUID.setText(iBeacon.getUUID());
//	viewHolder.ibeaconDistance.setText(
//			mContext.getString(R.string.formatter_meters, accuracy));
//	viewHolder.ibeaconDistanceDescriptor.setText(iBeacon.getDistanceDescriptor().toString());
//}

	private static String intToHex(int n,int length) {
		StringBuffer s = new StringBuffer();
		String a;
		char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		while(n != 0){
			s = s.append(b[n%16]);
			n = n/16;
		}
		a = s.reverse().toString();
		int addZero = length- a.length();
		if (addZero > 0) {
			for (int i = 0; i < addZero; i++) {
				a = "0" + a;
			}
		}
		return a;
	}






	private int getPower() {
		int battery = 0;
		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
				BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
				battery = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
			} else {
				Intent intent = new ContextWrapper(getApplicationContext()).
						registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
				battery =  (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
						intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
			}
		} catch (Exception e) {
		    if (e != null) {
		        Log.e("",""+e.toString());
		    }
			PgyerSDKManager.reportException(e);
		}

		return battery;
	}



}
